<template>
  <div class="wrap-container">
    <div class="data_item">
      <div class="data_top flexBetween">
        <div class="data_tit">
          <div class="line"></div>
          <p>数据概况</p>
          <el-tooltip
            class="item"
            effect="dark"
            content="      "
            placement="right-start"
            popper-class="popperStyle"
          >
            <template #content>
              <div class="tips_cont">
                <p>注意：</p>
                <p>
                  1.订单相关数据以下单时间统计，支付相关数据以支付成功时间统计，订单查询页面根据下单时间查询对应的订单，如客户当日下单，次日支付，则下单与支付数据会有时间差。
                </p>
                <p>
                  2.浏览量：统计时间内，小程序被访问的次数，一个人在统计时间内访问多次记为多次。
                </p>
                <p>
                  3.访客数：统计时间内，小程序被访问的去重人数，一个人在统计时间范围内访问多次只记为一个。
                </p>
                <p>
                  4.访问量：统计时间内，小程序被访问的次数，一个人在统计时间范围内访问多次，记录多次。
                </p>
              </div>
            </template>
            <img src="@/assets/images/icon/tips_icon.png" />
          </el-tooltip>
        </div>
        <div class="tabs_day align_center">
          <div
            :class="['tabs_item', { active: item.id == queryParams.dataType }]"
            v-for="item in tabsList"
            :key="item.id"
            @click="changeTabs(item.id)"
          >
            {{ item.name }}
          </div>
          <div class="select_date">
            <el-date-picker
              v-model="queryParams.date"
              type="date"
              placeholder="请选择日期"
              value-format="yyyy-MM-dd"
              @change="changeDate"
            >
            </el-date-picker>
          </div>
        </div>
      </div>
      <el-row :gutter="15" class="view-box">
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">
                  <template v-if="queryParams.dataType == 1">今日预约</template>
                  <template v-else>预约量</template>
                </p>
                <p class="view-num">{{ profileData.orderCount }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayPlaceOrderCount }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.orderStatus == 1,
                    drop_style: profileData.orderStatus == 2,
                  }"
                  >{{ profileData.orderRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.orderStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.orderStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">
                  <template v-if="queryParams.dataType == 1">今日浏览</template>
                  <template v-else>浏览量</template>
                </p>
                <p class="view-num">{{ profileData.viewCount }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayViewCount }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.viewStatus == 1,
                    drop_style: profileData.viewStatus == 2,
                  }"
                  >{{ profileData.viewRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.viewStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.viewStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">
                  <template v-if="queryParams.dataType == 1">今日收藏</template>
                  <template v-else>收藏量</template>
                </p>
                <p class="view-num">{{ profileData.likeCount }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayLikeCount }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.likeStatus == 1,
                    drop_style: profileData.likeStatus == 2,
                  }"
                  >{{ profileData.likeRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.likeStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.likeStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">下单人数（人）</p>
                <p class="view-num">{{ profileData.placeOrderCount }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayPlaceOrderCount }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.placeOrderStatus == 1,
                    drop_style: profileData.placeOrderStatus == 2,
                  }"
                  >{{ profileData.placeOrderRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.placeOrderStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.placeOrderStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">下单数量（单）</p>
                <p class="view-num">{{ profileData.placeOrderCount }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayPlaceOrderCount }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.placeOrderStatus == 1,
                    drop_style: profileData.placeOrderStatus == 2,
                  }"
                  >{{ profileData.placeOrderRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.placeOrderStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.placeOrderStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">实付订单金额(元)</p>
                <p class="view-num">{{ profileData.paymentMoney }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">
                  {{ profileData.yesterdayPaymentMoney }}
                </p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.paymentStatus == 1,
                    drop_style: profileData.paymentStatus == 2,
                  }"
                  >{{ profileData.paymentRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.paymentStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.paymentStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="view-item">
            <div class="view-info">
              <div class="view-l">
                <p class="view-label">应付订单金额(元)</p>
                <p class="view-num">{{ profileData.countMoney }}</p>
              </div>
              <div class="view-r" v-if="queryParams.dataType == 1">
                <p class="yesterday">昨日</p>
                <p class="yesterday-num">{{ profileData.yesterdayMoney }}</p>
              </div>
            </div>
            <div class="compare" v-if="queryParams.dataType == 1">
              较昨日
              <p>
                <span
                  :class="{
                    up_style: profileData.moneyStatus == 1,
                    drop_style: profileData.moneyStatus == 2,
                  }"
                  >{{ profileData.moneyRate }}</span
                >
                <img
                  :src="`/src/assets/images/icon/${
                    profileData.moneyStatus == 1 ? 'up_icon' : 'drop_icon'
                  }.png`"
                  alt=""
                  v-if="profileData.moneyStatus != 0"
                />
              </p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="data_item">
      <div class="data_top flexBetween">
        <div class="data_tit">
          <div class="line"></div>
          <p>预约信息</p>
        </div>
        <div class="search">
          <el-input
            clearable
            v-model="queryParams2.inputData"
            prefix-icon="Search"
            placeholder="请输入用户名/手机号/类型"
            @input="changeInput"
          ></el-input>
        </div>
      </div>
      <div class="table_box">
        <el-table v-loading="reservateLoading" :data="reservateList">
          <el-table-column label="ID" width="60">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="用户" prop="realName" width="80">
            <template #default="{ row }">
              {{ row.realName || '匿名用户' }}
            </template>
          </el-table-column>
          <el-table-column
            label="手机号"
            prop="orderPhone"
            width="120"
            v-hasPermi="['sys:order:btn_show_phone']"
          ></el-table-column>
          <el-table-column label="用户类型" prop="userType" width="90">
            <template #default="{ row }">
              {{ row.userType || '普通用户' }}
            </template>
          </el-table-column>
          <el-table-column label="订单来源" prop="userSource" width="90">
            <template #default="{ row }">
              {{ row.userSource || '小程序' }}
            </template>
          </el-table-column>
          <el-table-column label="订单号" prop="orderNo"></el-table-column>
          <el-table-column label="下单时间 " prop="createTime" width="180"></el-table-column>
          <el-table-column label="运动类型" prop="type" width="90"></el-table-column>
          <el-table-column label="场地" prop="siteName" width="140">
            <template #default="{ row }">
              <div class="cell_item" v-for="(item, index) in row.siteList" :key="index">
                {{ item }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="预约时段 " width="120">
            <template #default="{ row }">
              <div class="cell_item" v-for="(item, index) in row.timeList" :key="index">
                {{ item }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" prop="orderMoney" width="100"></el-table-column>
          <el-table-column label="优惠券" prop="discountAmount" width="100">
            <template #default="{ row }">
              {{ row.discountAmount || '--' }}
            </template>
          </el-table-column>
          <el-table-column label="实付金额" prop="paymentAmount" width="100"></el-table-column>
          <el-table-column label="附加信息" width="90">
            <template #default="{ row }"
              ><span>{{ row.orderRemarks || '--' }}</span></template
            >
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="{ row }">
              <el-button type="text" @click="orderDetail(row.orderId)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="reservateTotal > 0"
          :total="reservateTotal"
          v-model:page="queryParams2.pageNum"
          v-model:limit="queryParams2.pageSize"
          @pagination="getReservate"
        />
      </div>
    </div>
    <div class="data_item">
      <div class="data_top flexBetween">
        <div class="data_tit">
          <div class="line"></div>
          <p>评论管理（{{ commentTotal }}条）</p>
        </div>
        <div class="search_comment">
          <el-input
            v-model="queryParams3.inputData"
            placeholder="请输入用户 / 订单号 / 关键字"
            clearable
          ></el-input>
          <el-date-picker
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            v-model="dateArr"
            value-format="yyyy-MM-dd"
            @change="changeDateRange"
          >
          </el-date-picker>
          <el-button type="primary" @click="queryComment">查询</el-button>
          <el-button type="primary" @click="resetComment">重置</el-button>
        </div>
      </div>
      <div class="table_box">
        <el-table v-loading="commentLoading" :data="commentList">
          <el-table-column label="评论内容" width="500">
            <template #default="{ row }">
              <div class="comment_cont">
                <div class="rate">
                  <el-rate v-model="row.star" disabled show-score text-color="#ff9900"> </el-rate>
                </div>
                <p>{{ row.content }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="用户ID" prop="realName" width="160"></el-table-column>
          <el-table-column label="订单号" prop="orderNo"></el-table-column>
          <el-table-column label="下单时间" prop="createTime"></el-table-column>
          <el-table-column label="运动类型" prop="type" width="200"></el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="{ row }">
              <!-- <el-button type="text">查看</el-button>
              <el-button type="text">回复</el-button> -->
              <el-button type="text" @click="updateEvaluateStatus(row)">{{
                row.status == 0 ? '隐藏' : '显示'
              }}</el-button>
              <el-button type="text" @click="handleDelComment(row.id)">删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="commentTotal > 0"
          :total="commentTotal"
          v-model:page="queryParams3.pageNum"
          v-model:limit="queryParams3.pageSize"
          @pagination="getComment"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getDataProfiling,
  getOrderListByStadiumId,
  getEvaluateListByStadiumId,
  delEvaluateById,
  updateEvaluateStatus as updateEvaluateStatusApi,
} from '@/api/stadium/stadium'
import Pagination from '@/components/Pagination/index.vue'

// 定义类型
interface TabsItem {
  id: number
  name: string
}

interface ProfileData {
  orderCount: number
  yesterdayPlaceOrderCount: number
  orderStatus: number
  orderRate: string
  viewCount: number
  yesterdayViewCount: number
  viewStatus: number
  viewRate: string
  likeCount: number
  yesterdayLikeCount: number
  likeStatus: number
  likeRate: string
  placeOrderCount: number
  placeOrderStatus: number
  placeOrderRate: string
  paymentMoney: number
  yesterdayPaymentMoney: number
  paymentStatus: number
  paymentRate: string
  countMoney: number
  yesterdayMoney: number
  moneyStatus: number
  moneyRate: string
}

interface ReservateItem {
  orderId: number
  realName: string
  orderPhone: string
  userType: string
  userSource: string
  orderNo: string
  createTime: string
  type: string
  siteList: string[]
  timeList: string[]
  orderMoney: number
  discountAmount: number
  paymentAmount: number
  orderRemarks: string
}

interface CommentItem {
  id: number
  star: number
  content: string
  realName: string
  orderNo: string
  createTime: string
  type: string
  status: number
  imgs: string[]
}

// 使用路由和路由器
const route = useRoute()
const router = useRouter()

// 定义响应式数据
const tabsList = ref<TabsItem[]>([
  { id: 1, name: '今天' },
  { id: 2, name: '7天' },
  { id: 3, name: '近30天' },
  { id: 4, name: '近1年' },
])

const profileData = ref<ProfileData>({} as ProfileData)
const reservateList = ref<ReservateItem[]>([])
const commentList = ref<CommentItem[]>([])
const reservateLoading = ref(false)
const commentLoading = ref(false)

const queryParams = reactive({
  dataType: 1 as number | null,
  date: null as string | null,
})

const queryParams2 = reactive({
  pageNum: 1,
  pageSize: 10,
  inputData: null as string | null,
})

const queryParams3 = reactive({
  pageNum: 1,
  pageSize: 10,
  inputData: '',
  dateStart: null as string | null,
  dateEnd: null as string | null,
})

const commentTotal = ref(0)
const dateArr = ref<any[]>([])
const reservateTotal = ref(0)
const stadiumId = ref<string | null>(null)

// 组件创建时获取数据
onMounted(() => {
  stadiumId.value = route.query.id as string
  getDataProfile()
  getReservate()
  getComment()
})

// 获取场馆数据概况
const getDataProfile = async () => {
  const params = {
    ...queryParams,
    stadiumId: stadiumId.value,
  }
  const { data } = await getDataProfiling(params)
  profileData.value = data
}

// 数据概况选项切换
const changeTabs = (id: number) => {
  queryParams.dataType = id
  queryParams.date = null
  getDataProfile()
}

// 数据概况时间选择
const changeDate = () => {
  console.log(queryParams, 'queryParams')
  queryParams.dataType = null
  getDataProfile()
}

// 预约信息搜索用户名 手机号 类型
const changeInput = () => {
  queryParams2.pageNum = 1
  getReservate()
}

// 获取预约信息
const getReservate = async () => {
  reservateLoading.value = true
  const params = {
    ...queryParams2,
    stadiumId: stadiumId.value,
  }
  try {
    const res = await getOrderListByStadiumId(params)
    reservateList.value = res.rows
    reservateTotal.value = res.total
  } finally {
    reservateLoading.value = false
  }
}

// 订单详情
const orderDetail = (id: number) => {
  router.push({
    path: '/order/detail',
    query: { id },
  })
}

// 评论选择时间范围
const changeDateRange = (val: (string | null)[] | null) => {
  if (val && val.length > 0) {
    queryParams3.dateStart = val[0] ?? null
    queryParams3.dateEnd = val[1] ?? null
  } else {
    queryParams3.dateStart = null
    queryParams3.dateEnd = null
  }
}

// 获取评论留言
const getComment = async () => {
  commentLoading.value = true
  const params = {
    ...queryParams3,
    stadiumId: stadiumId.value,
  }
  try {
    const res = await getEvaluateListByStadiumId(params)
    commentList.value = res.rows
    commentTotal.value = res.total
    commentList.value.forEach((item: CommentItem) => {
      item.imgs = item.imgs || [] // 确保imgs数组存在
      item.star = Number(item.star)
    })
  } finally {
    commentLoading.value = false
  }
}

// 评论查询
const queryComment = () => {
  queryParams3.pageNum = 1
  getComment()
}

// 重置查询条件
const resetComment = () => {
  queryParams3.inputData = ''
  queryParams3.dateStart = null
  queryParams3.dateEnd = null
  dateArr.value = []
  getComment()
}

// 删除留言
const handleDelComment = (id: number) => {
  // 这里需要使用全局的 $modal 方法，但在 Vue 3 中我们需要替换它
  if (window.confirm('是否确认删除选中的数据项？')) {
    delEvaluateById(id)
      .then(() => {
        getComment()
        // 替代 this.$modal.msgSuccess("删除成功")
        alert('删除成功')
      })
      .catch(() => {})
  }
}

// 隐藏显示留言
const updateEvaluateStatus = (row: CommentItem) => {
  if (window.confirm(`是否确认${row.status == 0 ? '隐藏' : '显示'}选中的数据项？`)) {
    updateEvaluateStatusApi({
      id: row.id,
      status: row.status == 0 ? 1 : 0,
    })
      .then(() => {
        getComment()
        // 替代 this.$modal.msgSuccess("操作成功")
        alert('操作成功')
      })
      .catch(() => {})
  }
}
</script>

<style lang="scss" scoped>
.data_item {
  background: #fff;
  padding: 16px 15px 24px;
  margin-bottom: 15px;
  .data_top {
    .data_tit {
      display: flex;
      align-items: center;
      .line {
        width: 5px;
        height: 18px;
        background: #0988fb;
      }
      p {
        font-size: 16px;
        line-height: 24px;
        margin: 0 8px;
      }
    }
    .tabs_day {
      .tabs_item {
        height: 27px;
        line-height: 27px;
      }
    }
    .select_date {
      margin-left: 14px;
      :deep(.el-date-editor) {
        width: 113px;
        height: 27px;
        .el-input__inner {
          height: 27px;
          line-height: 27px;
          padding-right: 10px;
          font-size: 12px;
        }
        .el-input__icon {
          line-height: 27px;
        }
      }
    }
    .search {
      :deep(.el-input) {
        width: 284px;
        height: 37px;
        .el-icon-search:before {
          font-size: 23px;
          color: #808080;
        }
        .el-input__prefix {
          left: 8px;
        }
        .el-input__inner {
          height: 37px;
          line-height: 37px;
          padding-left: 49px;
          border-radius: 8px;
        }
      }
    }
  }
  .view-box {
    margin-top: 23px;
    display: flex;
    justify-content: space-between;
    .el-col-3 {
      width: 14.2%;
      max-width: 14.2%;
      flex: 0 0 14.2%;
    }
    .view-item {
      background: #f5faff;
      border-radius: 12px;
      font-size: 14px;
      color: #383838;
      padding: 22px 9px 24px 13px;
      .view-info {
        display: flex;
        justify-content: space-between;
        .view-label {
          line-height: 21px;
        }
        .view-num {
          font-size: 36px;
          line-height: 42px;
          margin-top: 23px;
        }
        .view-r {
          .yesterday {
            color: #808080;
          }
          .yesterday-num {
            font-size: 20px;
            color: #a6a6a6;
            line-height: 42px;
            margin-top: 28px;
          }
        }
      }
      .compare {
        display: flex;
        line-height: 30px;
        margin-top: 23px;
        p {
          margin-left: 2px;
          &.drop {
            span {
              color: #d43030 !important;
            }
          }
        }
        span {
          color: #2a82e4;
        }
        img {
          margin-left: 4px;
        }
      }
    }
  }
  .table_box {
    padding: 0;
    margin-top: 12px;
    :deep(.el-table) {
      .el-table__cell {
        padding: 10px 0 !important;
      }
    }
    .comment_cont {
      background: #f9f9f9;
      padding: 15px;
    }
    .rate {
      :deep(.el-rate__icon) {
        font-size: 20px;
        margin-right: -3px;
      }
      :deep(.el-rate__text) {
        margin-left: 6px;
      }
    }
  }
  :deep(.search_comment) {
    display: flex;
    .el-input,
    .el-date-editor {
      width: 234px;
      height: 37px;
      .el-input__inner {
        height: 37px;
        line-height: 37px;
        border-radius: 8px;
      }
    }
    .el-date-editor {
      margin: 0 15px;
    }
    .el-button {
      border-radius: 8px;
      width: 59px;
      padding: 0;
      & + .el-button {
        margin-left: 15px;
      }
    }
  }
}
</style>
